package it.test.socket.server;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;


class HttpHandler implements Runnable {

    private final Socket accept;

    public HttpHandler(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        if (accept == null) {
            return;
        }
        try {
            System.out.println("我收到一个请求:" + accept.getRemoteSocketAddress());
            //获取输入流
            InputStream inputStream = accept.getInputStream();
//            接收请求内容
//            byte[] bytes = new byte[1024 * 1024 * 1024];
//            int len = inputStream.read(bytes, 0, bytes.length);
//            String requestStr = new String(bytes, 0, len);
//            System.out.println(requestStr + "\n\n");

//            ObjectInputStream ois = new ObjectInputStream(inputStream);
//            SysUserOnline suo = (SysUserOnline)ois.readObject();
//            System.out.println(suo.toString() + "\n\n");

            // 创建一个BufferedReader对象，从Socket中读取JSON格式的字符串
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            String json = in.readLine();
//            SysUserOnline sysUserOnline = JSONUtil.toBean(json,SysUserOnline.class);
//            System.out.println(sysUserOnline.toString() + "\n\n");
            System.out.println(json + "\n\n");

            OutputStream outputStream = accept.getOutputStream();
            String response = "HTTP/1.1 200 OK\n" +
                    "Server: YuanaoServer\n" +
                    "Content-Type: text/html\n" +
                    "ok";
            outputStream.write(response.getBytes());
            outputStream.close();
            inputStream.close();
            accept.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
